import axios from 'axios'

export const state = () => ({
  locales: ['en', 'zh', 'cn'],
  locale: 'en',
  isAppAlive: false,
  isAppVisible: true,
  authUser: null,
  authURL: ''
})

export const mutations = {
  SET_LANG (state, locale) {
    if (state.locales.indexOf(locale) !== -1) {
      state.locale = locale
    }
  },
  SET_USER (state, user) { state.authUser = user },
  SET_ALIVE (state) { state.isAppAlive = true },
  TOGGLE_VISIBLE (state) { state.isAppVisible = !state.isAppVisible },
  // SET_VISIBLE (state) { state.isAppVisible = true },
  // SET_INVISIBLE (state) { state.isAppVisible = false },
  SET_AUTH_URL (state, url) { state.authURL = url }
}

export const actions = {
  // nuxtServerInit is called by Nuxt.js before server-rendering every page
  nuxtServerInit ({ commit }, { req }) {
    if (req.session && req.session.authUser) {
      commit('SET_USER', req.session.authUser)
    }
    if (req.session && req.session.locale) {
      commit('SET_LANG', req.session.locale.locale)
    }
  },

  async lang ({ commit }, locale) {
    try {
      const { data } = await axios.post('/api/lang', { locale })
      commit('SET_LANG', data.locale)
    } catch (error) {
      if (error.response && error.response.status === 401) {
        throw new Error('No language package')
      }
      throw error
    }
  },

  async signin ({ commit }, { username, password }) {
    try {
      const { data } = await axios.post('/api/signin', {
        username, password
      })
      commit('SET_USER', data)
    } catch (error) {
      if (error.response && error.response.status === 401) {
        throw new Error('Bad credentials')
      }
      throw error
    }
  },

  async signout ({ commit }) {
    await axios.post('/api/signout')
    commit('SET_USER', null)
  }

}
